package com.zlk.algorithm.huawei.leetcode.slidingWindow;

import org.junit.Test;

import java.util.HashMap;

/**
 * @program: algorithm
 * @ClassName Code34_longestSubarray
 * @description: 绝对差不超过限制的最长连续子数组
 * @author: slfang todo
 * @create: 2025-01-10 10:02
 * @Version 1.0
 **/
public class Code34_longestSubarray {

    public int longestSubarray(int[] nums, int limit) {
        int left = 0;
        int right = 0;
        int length = nums.length;
        int ans = 0;
        HashMap<Integer,Info> map = new HashMap<>();
        map.put(0,new Info(nums[0],nums[0],0));
        int dpMax = nums[0];
        int dpMin = nums[0];
        //激励
        while (right<length){
            //区间极值大于limit
            if (left<right&&Math.abs(dpMax-dpMin)>limit){
                //不符合缩小
                left++;
            }
            //符合统计当前值，扩大范围
            int count = right-left;
            ans = Math.max(count,ans);
            right++;
        }
        return -1;
    }

    class  Info{
        int max;
        int min;
        int end;

        public Info(int max, int min, int end) {
            this.max = max;
            this.min = min;
            this.end = end;
        }
    }


    //输入：nums = [8,2,4,7], limit = 4
    //输出：2
    //解释：所有子数组如下：
    //[8] 最大绝对差 |8-8| = 0 <= 4.
    //[8,2] 最大绝对差 |8-2| = 6 > 4.
    //[8,2,4] 最大绝对差 |8-2| = 6 > 4.
    //[8,2,4,7] 最大绝对差 |8-2| = 6 > 4.
    //[2] 最大绝对差 |2-2| = 0 <= 4.
    //[2,4] 最大绝对差 |2-4| = 2 <= 4.
    //[2,4,7] 最大绝对差 |2-7| = 5 > 4.
    //[4] 最大绝对差 |4-4| = 0 <= 4.
    //[4,7] 最大绝对差 |4-7| = 3 <= 4.
    //[7] 最大绝对差 |7-7| = 0 <= 4.
    //因此，满足题意的最长子数组的长度为 2 。


    //输入：nums = [10,1,2,4,7,2], limit = 5
    //输出：4
    //解释：满足题意的最长子数组是 [2,4,7,2]，其最大绝对差 |2-7| = 5 <= 5 。
    public int longestSubarrayOverTime(int[] nums, int limit) {
        int left = 0;
        int right = 0;
        int length = nums.length;
        int ans = 0;
        int preMax;
        int preMin;
        while (left<length){
            right = left;
            int startVal = nums[left];
            preMax = startVal;
            preMin = startVal;
            while (Math.abs(preMax-preMin)<=limit&&right<length){
                right++;
                if(right<length){
                    preMax = Math.max(preMax,nums[right]);
                    preMin = Math.min(preMin,nums[right]);
                }
            }
            ans = Math.max(ans,right-left);
            left++;
        }
        return ans;
    }
    @Test
    public void test(){
        int[] nums = new int[]{10,1,2,4,7,2};
        System.out.println(longestSubarray(nums, 5));
    }
}
